package com.example.mcp;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务管理器
 * 负责管理 MCP 服务器服务的启动、停止和状态检查
 */
public class ServiceManager {
    
    private static final Logger logger = LoggerFactory.getLogger(ServiceManager.class);
    private static final String TAG = "ServiceManager";
    
    private Context context;
    private McpServerService mcpServerService;
    private boolean isServiceBound = false;
    
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            McpServerService.McpServerBinder binder = (McpServerService.McpServerBinder) service;
            mcpServerService = binder.getService();
            isServiceBound = true;
            logger.info("🔗 MCP 服务器服务已连接");
        }
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mcpServerService = null;
            isServiceBound = false;
            logger.warn("🔌 MCP 服务器服务连接断开");
        }
    };
    
    public ServiceManager(Context context) {
        this.context = context;
    }
    
    /**
     * 启动 MCP 服务器服务
     */
    public void startMcpServerService() {
        try {
            Intent serviceIntent = new Intent(context, McpServerService.class);
            context.startForegroundService(serviceIntent);
            logger.info("🚀 MCP 服务器服务启动请求已发送");
        } catch (Exception e) {
            logger.error("❌ 启动 MCP 服务器服务失败", e);
        }
    }
    
    /**
     * 停止 MCP 服务器服务
     */
    public void stopMcpServerService() {
        try {
            Intent serviceIntent = new Intent(context, McpServerService.class);
            context.stopService(serviceIntent);
            logger.info("🛑 MCP 服务器服务停止请求已发送");
        } catch (Exception e) {
            logger.error("❌ 停止 MCP 服务器服务失败", e);
        }
    }
    
    /**
     * 绑定到 MCP 服务器服务
     */
    public void bindToMcpServerService() {
        if (!isServiceBound) {
            try {
                Intent serviceIntent = new Intent(context, McpServerService.class);
                context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
                logger.info("🔗 正在绑定到 MCP 服务器服务...");
            } catch (Exception e) {
                logger.error("❌ 绑定到 MCP 服务器服务失败", e);
            }
        }
    }
    
    /**
     * 解绑 MCP 服务器服务
     */
    public void unbindFromMcpServerService() {
        if (isServiceBound) {
            try {
                context.unbindService(serviceConnection);
                isServiceBound = false;
                mcpServerService = null;
                logger.info("🔌 已解绑 MCP 服务器服务");
            } catch (Exception e) {
                logger.error("❌ 解绑 MCP 服务器服务失败", e);
            }
        }
    }
    
    /**
     * 检查服务是否正在运行
     */
    public boolean isServiceRunning() {
        return mcpServerService != null && mcpServerService.isServerRunning();
    }
    
    /**
     * 获取服务状态信息
     */
    public String getServiceStatus() {
        if (mcpServerService == null) {
            return "服务未连接";
        }
        String baseStatus = mcpServerService.isServerRunning() ? "服务正在运行" : "服务已停止";
        return baseStatus;
    }
    
    /**
     * 获取详细服务状态信息（包括电源锁状态）
     */
    public String getDetailedServiceStatus() {
        if (mcpServerService == null) {
            return "服务未连接";
        }
        
        StringBuilder status = new StringBuilder();
        status.append(mcpServerService.isServerRunning() ? "服务正在运行" : "服务已停止");
        
        // 这里可以添加更多状态信息
        return status.toString();
    }
    
    /**
     * 清理资源
     */
    public void cleanup() {
        unbindFromMcpServerService();

        stopMcpServerService();
    }
}
